package com.baidu.validator;


import com.baidu.emus.ErrorCode;
import com.baidu.model.BDUser;
import com.baidu.model.MyTB;
import com.baidu.util.BaiDuApi;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.validate.Validator;

/**
 * 回帖设置验证
 * @author iicm
 * 2015-12-28 11:11
 */
public class ReplyValidator extends Validator{
	
	private static final String msg = "message";
	
	@Override
	protected void validate(Controller c) {
		setShortCircuit(true);
        validateRequired("reply.tbNames", msg, "请输入要回帖的贴吧");
        validateRequired("reply.tid", msg, "请输入帖子tid，随机回复请输入0");
        String tbNames = c.getPara("reply.tbNames");//贴吧名称
        String replyMod = c.getPara("reply.replyMod");//回帖模式
        String tids = c.getPara("reply.tid");//对应的帖子tid
        String bdGuid = c.getPara("reply.bdGuid");//百度guid
        BDUser user = BDUser.dao.findById(bdGuid);
        if(StrKit.notBlank(tbNames)){
			String[] arr = tbNames.split(",");
			String[] arr2 = tids.split(",");
			if(arr.length > 3){
				addError(msg, "您最多可设置3个贴吧");
			}
			if(arr.length != arr2.length){
				addError(msg, "贴吧与tid不一致");
			}
			for (int i = 0; i < arr.length; i++) {
				//模拟post验证
				MyTB tb = MyTB.dao.findByNameAndBdId(arr[i], bdGuid);
				if(tb == null){
					addError(msg, "尚未关注 <b>"+ arr[i] +"</b> 吧，请刷新贴吧列表");
				}
				if(!"0".equals(arr2[i])){
					try {
						//判断帖子所在的贴吧是否已关注，是否和当前贴吧对应
						Integer result = BaiDuApi.api.checkT(user.getStr("bduss"), "http://tieba.baidu.com/p/"+arr2[i], tb.getInt("fid").toString());
						if(result == -1){
							addError(msg, "tid为<b>"+ arr2[i] +"</b>的帖子所在贴吧尚未关注 ");
						}else if(result == -2){
							addError(msg, "tid为<b>"+ arr2[i] +"</b>的帖子不属于<b>"+ arr[i] +"吧</b> ");
						}else if(result == -3){
							addError(msg, "tid为<b>"+ arr2[i] +"</b>的帖子不存在 ");
						}
					} catch (Exception e) {
					}
				}else{
					if(Integer.parseInt(replyMod) == 1){
						addError(msg, "盖楼顶贴模式下需要指定贴吧tid");
					}
				}
			}
		}
	}

	@Override
	protected void handleError(Controller c) {
		c.setAttr("status",ErrorCode.replyError.getCode());
		c.keepPara();
		c.renderJson();
	}

}
